package net.androy.hoola;

import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class XMLHandler extends DefaultHandler {

    private List horoscopes;
    private String currentNode;
    private boolean inItem = false;
    private HoroscopeItem item;
    private String data;

    public XMLHandler(List horoscopes) {
	this.horoscopes = horoscopes;
    }

    @Override
    public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
	if (localName.equals("item")) {
	    inItem = true;
	    item = new HoroscopeItem();

	}

	currentNode = localName;
    }

    @Override
    public void endElement(String uri, String localName, String name) throws SAXException {

	if (localName.equals("item")) {
	    inItem = false;
	    horoscopes.add(item);
	}

	if (localName.equals("title")) {
	    if (data != null && data.trim().length() > 0) {
		item.setTitle(data.trim().replaceAll("\\r", "").replaceAll("null", ""));
		data = "";
	    }
	} else if (localName.equals("description")) {
	    if (data != null && data.trim().length() > 0) {
		String s = data.trim();
		item.setDescription(s.substring(s.indexOf("<p>") + 3, s.indexOf("</p>", s.indexOf("<p>") + 3)));
		data = "";
	    }
	}
    }

    @Override
    public void characters(char[] ch, int start, int length) throws SAXException {
	if (inItem && currentNode != null && currentNode.equals("title")) {
	    data += new String(ch, start, length);
	}else if(inItem && currentNode != null && currentNode.equals("description")){
		data += new String(ch, start, length);
	}
    }
}
